package element.synt;

import element.ast.AstNode;
import element.ast.DopNode;
import element.ast.PrimNode;
import element.base.Synt;
import element.base.TreeNode;
import element.base.Word;
import intermediate_representation.AssignRP;
import table.InterCodeTable;

public class AddExp extends Synt {
    public AstNode toAst() {
        if (this.isConst()) {
            return new PrimNode(this.calcu());
        }
        TreeNode node0 = this.getNodes().get(0);
        if (node0 instanceof MulExp) {
            return ((MulExp) node0).toAst();
        } else {
            MulExp right = (MulExp) this.getNodes().get(2);
            AddExp left = (AddExp) node0;
            String op = ((Word) this.getNodes().get(1)).getContent();
            AstNode leftNode = left.toAst();
            AstNode rightNode = right.toAst();
            return new DopNode(op, leftNode, rightNode);
        }
    }

    public int calcu() {
        TreeNode node0 = this.getNodes().get(0);
        if (node0 instanceof MulExp) {
            return ((MulExp) node0).calcu();
        } else {
            MulExp right = (MulExp) this.getNodes().get(2);
            AddExp left = (AddExp) node0;
            String op = ((Word) this.getNodes().get(1)).getContent();
            int leftvalue = left.calcu();
            int rightvalue = right.calcu();
            if (op.equals("+")) {
                return leftvalue + rightvalue;
            } else {
                return leftvalue - rightvalue;
            }
        }
    }

    public boolean isConst() {
        TreeNode node0 = this.getNodes().get(0);
        if (node0 instanceof MulExp) {
            return ((MulExp) node0).isConst();
        } else {
            MulExp right = (MulExp) this.getNodes().get(2);
            AddExp left = (AddExp) node0;
            String op = ((Word) this.getNodes().get(1)).getContent();
            return left.isConst() && right.isConst();
        }
    }

    public void toInterRP() {
        if (this.isConst()) {
            int res = this.calcu();
            InterCodeTable.pushvar();
            String returns = InterCodeTable.nowVar;
            AssignRP assignRP = new AssignRP(returns, String.valueOf(res));
            InterCodeTable.addCode(assignRP);
        } else {
            AstNode astNode = this.toAst();
            astNode.tointerRP();
        }
    }
}
